from nicegui import ui
import aiohttp
import ssl

# 创建全局状态控制变量
loading = False
API_KEY = "sk-69cd183139d8439daa7fabc2a94498bd"
API_URL = "https://api.deepseek.com/v1/chat/completions"


async def process_text():
    global loading
    try:
        loading = True
        progress.visible = True
        submit_btn.disable()

        raw_input = input_text.value.strip()
        if not raw_input:
            ui.notify("请输入有效内容", type="warning")
            return

        ssl_ctx = ssl.create_default_context()
        ssl_ctx.options |= ssl.OP_NO_SSLv2 | ssl.OP_NO_SSLv3
        ssl_ctx.minimum_version = ssl.TLSVersion.TLSv1_2

        payload = {
            "model": "deepseek-chat",
            "messages": [{
                "role": "user",
                "content": "请直接回答以下问题，不要添加建议联网的提示：" + raw_input
            }],
            "temperature": 0.7,
            "max_tokens": 1000
        }

        async with aiohttp.ClientSession(
                connector=aiohttp.TCPConnector(ssl=ssl_ctx),
                timeout=aiohttp.ClientTimeout(total=30)
        ) as session:
            async with session.post(
                    API_URL,
                    headers={"Authorization": f"Bearer {API_KEY}"},
                    json=payload
            ) as response:
                raw_response = await response.text()
                if response.status == 200:
                    data = await response.json()
                    output_text.value = data['choices'][0]['message']['content']
                else:
                    output_text.value = f"请求失败（状态码 {response.status}）\n{raw_response[:300]}"

    except Exception as e:
        output_text.value = f"处理异常：{str(e)}"
        ui.notify("处理请求时发生错误", type="negative")
    finally:
        loading = False
        progress.visible = False
        submit_btn.enable()


def clear_text():
    input_text.value = ""
    output_text.value = ""


# 界面布局
with ui.card().classes("w-full h-screen p-8 gap-4"):
    ui.label("DeepSeek 智能助手").classes("text-2xl font-bold text-blue-600 mb-8")

    with ui.grid(columns=2).classes("w-full h-[70vh] gap-6"):
        input_text = ui.textarea(label="输入内容").props("outlined autogrow").classes("resize text-lg")
        output_text = ui.textarea(label="处理结果").props("outlined readonly autogrow").classes("text-lg")

    # 加载进度条
    with ui.row().classes("w-full justify-center"):
        progress = ui.spinner(size="lg", color="blue").bind_visibility_from(globals(), "loading")

    # 操作按钮组
    with ui.row().classes("w-full justify-center gap-4 mt-6"):
        submit_btn = ui.button("提交处理", on_click=process_text).props("icon=send color=primary").classes("px-8 py-4")
        ui.button("清空内容", on_click=clear_text).props("icon=delete color=negative").classes("px-8 py-4")

ui.run(
    title="DeepSeek智能助手",
    reload=False,
    host='127.0.0.1',
    port=8080,
    dark=True
)